package com.goparry.taskman;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.goparry.taskman.restclient.RESTUtilities;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Environment;


public final class TaskManUtils {

	static private boolean STANDALONE = false;
		
	static private String session = null;

	static private SharedPreferences SETTINGS;
	
	protected TaskManUtils() {
	}

	public static void loadSettings(SharedPreferences settings) {
	    // Get any saved preferences
		SETTINGS = settings;
	    // get the last saved SERVER from preferences
	    String server = SETTINGS.getString("SERVER", "");
	    RESTUtilities.setServerAsString(server); 		
	}
	public static void saveServerPrefs(String server) {
		SharedPreferences.Editor editor = SETTINGS.edit();
		editor.putString("SERVER", server);
		editor.commit();
	}
	
	public static boolean isStandalone() {
		return STANDALONE;
	}
	/**
	 * Indicates whether the specified action can be used as an intent. This
	 * method queries the package manager for installed packages that can
	 * respond to an intent with the specified action. If no suitable package is
	 * found, this method returns false.
	 *
	 * @param context The application's environment.
	 * @param action The Intent action to check for availability.
	 *
	 * @return True if an Intent with the specified action can be sent and
	 *         responded to, false otherwise.
	 */
	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list =
			packageManager.queryIntentActivities(intent,
					PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}
	public static boolean saveContent(String ID, String path, String filename) {
		// Check if the file already exists and has the same size
		String uri = "SERVER" + "object/content?token=" + session + "&id=" + ID;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(uri);
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream instream = entity.getContent();
				OutputStream out = new FileOutputStream(path + "/" + filename);
				int len;
				byte[] buf = new byte[2048];
				while ((len = instream.read(buf)) != -1) {
					out.write(buf,0,len);
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	public static void saveContentStandalone(String ID, String path, String filename) {
		try {
		// TODO Need to download the file and check the size
			String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
			InputStream in = new FileInputStream(sdcardPath + "/download/D-C-0012.pdf");
			OutputStream out = new FileOutputStream(path + "/" + filename);
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf,0,len);
			}
			in.close();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
    public static File createTempFile(String path, String filename, String text) throws IOException {
        File file = new File(path, filename);
        if (!file.exists()) file.createNewFile();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write(text);
        writer.close();
        return file;
    }
}

